package com.kitty.game.fight.task;

import com.kitty.game.fight.bean.Fight;
import com.kitty.game.fight.bean.FightObject;
import com.kitty.common.utils.SpringUtils;
import com.kitty.game.enter.FiedValue;
import com.kitty.game.enter.RespUpdate;
import com.kitty.game.fight.service.FightExecutorService;
import com.kitty.game.fight.service.FightService;
import com.kitty.mina.message.MessagePusher;

import java.util.Collections;

public class TimeOutTask implements FightingTask {


	private int fightId;

	public TimeOutTask(int fightId) {
		super();
		this.fightId = fightId;
	}

	@Override
	public void run() {
		FightService fightService = SpringUtils.getBean(FightService.class);
		Fight fight = fightService.getFight(fightId);
		if (fight == null) {
//			logger.error("定时器找不到数据{}", this);
			return;
		}

		fight.cancelTask(fight.getTimeOutTask());
		FightExecutorService fightExecutorService = SpringUtils.getBean(FightExecutorService.class);
		fightExecutorService.addFightTask(fight, this::timeOutAction);
	}

	private void timeOutAction() {
		FightService fightService = SpringUtils.getBean(FightService.class);
		Fight fight = fightService.getFight(fightId);
		// 删除宠物和人物的定时器
		for (FightObject fightObject : fight.getAllFightObjects()) {
			fight.removeHostTask(fightObject.getId());
			fight.removePetTask(fightObject.getId());
		}

		/**直接把全部的对象拿出来判断 不判断是不是PK战斗*/
		for (FightObject fightObject : fight.getAllFightObjects()) {
			if (!fightObject.isDoAction()) {
				if(fightObject.isPlayer()){
					fightObject.getRole().setAutoFight((byte) 1);
					RespUpdate respUpdate = new RespUpdate();
					respUpdate.setList(Collections.singletonList(new FiedValue(307,1,1)));
					respUpdate.setRoleId(fightObject.getId());
					MessagePusher.pushMessage(fightObject.getRole(), respUpdate);
				}
                if(fightObject.isPlayer() || fightObject.isPet()){
                    fightObject.setAutoFight((byte) 1);
                    fightService.autoFightOne(fight, fightObject,100);
                }

			}
		}
	}
}
